import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoAPI } from '@/services/login'

// 定义 Store
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const user = ref({})
    const getUser = async () => {
      const res = await userGetInfoAPI()
      user.value = res.data
    }
    const isLogin = () => {
      return token.value !== ''
    }
    const setToken = (newToken) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }

    const setUser = (newUser) => {
      user.value = newUser
    }

    const logOut = () => {
      token.value = ''
      user.value = {}
    }

    return {
      user,
      setUser,
      getUser,
      token,
      setToken,
      removeToken,
      isLogin,
      logOut,
    }
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value) // [!code warning]
        },
        getItem(key) {
          return uni.getStorageSync(key) // [!code warning]
        },
      },
    },
  },
)
